<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-alert title="添加商品信息" type="info" :closable="false" show-icon center></el-alert>
      <el-steps :space="200" :active="activeIndex - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <el-form ref="addFormRef" :model="addForm" :rules="addFormRules" label-position="top">
        <el-tabs
          v-model="activeIndex"
          tab-position="left"
          :before-leave="beforeTabLeave"
          @tab-click="handleTabClick"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="name">
              <el-input v-model="addForm.name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="price">
              <el-input v-model="addForm.price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="weight">
              <el-input v-model="addForm.weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="stockQuantity">
              <el-input v-model="addForm.stockQuantity" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="categoryIds">
              <el-cascader
                :options="categoryList"
                :props="cascaderProps"
                v-model="addForm.categoryIds"
                @change="categoryChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              v-for="item in dynamicAttributeList"
              :key="item.id"
              :label="item.attrName"
            >
              <el-checkbox-group v-model="item.attrVals">
                <el-checkbox v-for="(val,i) in item.attrVals" :label="val" :key="i" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item v-for="item in staticAttributeList" :key="item.id" :label="item.attrName">
              <el-input v-model="item.attrVals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              :action="uploadAction"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="uploadHeaders"
              :on-success="handleSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addForm.introduce" ref="xQuillEditor"></quill-editor>
            <el-button type="primary" class="btnAdd" @click="saveGoods">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <el-dialog
      title="图片预料"
      :visible.sync="previewDialogVisible"
      width="50%"
      @close="previewDialogClosed"
    >
      <img :src="previewPath" class="previewImg" />
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      activeIndex: '0',
      addForm: {
        name: '',
        price: '',
        weight: '',
        stockQuantity: '',
        categoryIds: [],
        introduce: '',
        images: [],
        attrs: []
      },
      addFormRules: {
        name: [
          { required: true, message: '商品名称不能为空', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '商品价格不能为空', trigger: 'blur' }
        ],
        weight: [
          { required: true, message: '商品重量不能为空', trigger: 'blur' }
        ],
        stockQuantity: [
          { required: true, message: '商品数量不能为空', trigger: 'blur' }
        ],
        categoryIds: [
          { required: true, message: '商品分类不能为空', trigger: 'blur' }
        ]
      },
      categoryList: [],
      cascaderProps: {
        expandTrigger: 'hover',
        value: 'catId',
        label: 'catName',
        children: 'children'
      },
      dynamicAttributeList: [],
      staticAttributeList: [],
      uploadAction: this.$global.baseUrl + '/goods/pic/upload',
      uploadHeaders: {
        Authorization: window.sessionStorage.getItem('token')
      },
      previewPath: '',
      previewDialogVisible: false
    }
  },
  created() {
    this.getCategoryList()
  },
  methods: {
    async getCategoryList() {
      const { data: result } = await this.$http.get('/categories')
      if (result.status !== 200) {
        return this.$message.error('获取分类数据失败！')
      }

      this.categoryList = result.data
    },
    categoryChange() {
      if (this.addForm.categoryIds.length !== 3) {
        this.addForm.categoryIds = []
        return null
      }
    },
    beforeTabLeave(targetName, sourceName) {
      if (sourceName === '0' && !this.categoryId) {
        this.$message.error('请选择商品分类！')
        return false
      }
    },
    async handleTabClick() {
      if (this.activeIndex === '1' && this.categoryId) {
        const { data: result } = await this.$http.get(`/categories/${this.categoryId}/attributes`, { params: { attrSel: 'many' } })
        if (result.status === 200) {
          if (result.data) {
            result.data.forEach(item => {
              item.attrVals = item.attrVals ? item.attrVals.split(' ') : null
            })
          }
          this.dynamicAttributeList = result.data
        }
      } else if (this.activeIndex === '2') {
        const { data: result } = await this.$http.get(`/categories/${this.categoryId}/attributes`, { params: { attrSel: 'only' } })
        if (result.status === 200) {
          this.staticAttributeList = result.data
        }
      }
    },
    handlePreview(file) {
      this.previewPath = this.$global.baseUrl + file.response.data.imagePath
      this.previewDialogVisible = true
    },
    handleRemove(file) {
      const imagePath = file.response.data.imagePath
      const i = this.addForm.images.indexOf(imagePath)
      this.addForm.images.splice(i, 1)
    },
    handleSuccess(resp) {
      this.addForm.images.push(resp.data.imagePath)
    },
    previewDialogClosed() {
      // TODO
    },
    saveGoods() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
          return this.$message.error('请填写必要的表单项！')
        }

        // 处理表单数据
        const postData = {}
        postData.name = this.addForm.name
        postData.price = this.addForm.price
        postData.weight = this.addForm.weight
        postData.stockQuantity = this.addForm.stockQuantity
        postData.categoryIds = this.addForm.categoryIds.join(',')
        postData.introduce = this.addForm.introduce
        postData.images = this.addForm.images.join(',')
        postData.attrs = { 'dynamicAttributeList': [], 'staticAttributeList': [] }
        const dynamicAttrs = []
        const staticAttrs = []

        this.dynamicAttributeList.forEach(item => {
          const attrItem = {}
          attrItem.id = item.id
          attrItem.attrName = item.attrName
          attrItem.attrVals = item.attrVals.join(' ')
          dynamicAttrs.push(attrItem)
        })

        this.staticAttributeList.forEach(item => {
          const attrItem = {}
          attrItem.id = item.id
          attrItem.attrName = item.attrName
          attrItem.attrVals = item.attrVals
          staticAttrs.push(attrItem)
        })
        postData.attrs.dynamicAttributeList = dynamicAttrs
        postData.attrs.staticAttributeList = staticAttrs

        const { data: result } = await this.$http.post(`/goods`, postData)
        if (result.status !== 200) {
          return this.$message.error('添加商品出错！')
        }

        this.$message.success('添加商品成功！')
      })
    }
  },
  computed: {
    categoryId() {
      if (this.addForm.categoryIds.length === 3) {
        return this.addForm.categoryIds[2]
      }
      return null
    }
  }
}
</script>

<style scoped lang="less">
.el-cascader {
  width: 240px;
}

.el-checkbox {
  margin: 0 10px 0 0 !important;
}
.previewImg {
  width: 100%;
}
.btnAdd {
  margin-top: 15px;
}
</style>
